var container = document.getElementById("container");
var content = document.getElementById("content");
var refreshElem = document.getElementById("more");
var diff = container.offsetHeight - content.offsetHeight - 50;
// Initialize Scroller
var scroller = new Scroller(render, {
  scrollingX: false
});
// Activate pull-to-refresh
function dd() {
  scroller.activatePullToRefresh(diff, function() {
    // refreshElem.className += " active";
    refreshElem.innerHTML = "加载中...";
  }, function() {}, function() {
    // refreshElem.className += " running";
    refreshElem.innerHTML = '加载中...';
    setTimeout(function() {
      refreshElem.className = refreshElem.className.replace("running", "");
      insertItems();
      scroller.finishPullToRefresh();
    }, 2000);
  });
}
// Setup Scroller
dd();
var rect = container.getBoundingClientRect();
scroller.setPosition(rect.left + container.clientLeft, rect.top + container.clientTop);

// Fill Scroller
// console.log(content.children.length)
var insertItems = function() {
  for (var i = 0; i < 14; i++) {
    var row = document.createElement("li");
    row.className = "popular__item";
    row.innerHTML = '<a href="detail.html"><span class="commodity__img"><img src="../images/material_commodity_01.png"></span><p class="commodity__txt">自然之宝关 Osteo 国原装氨糖软骨素</p></a><div class="commodity__live tj"><span class="dib vm commodity__live_price">&yen;1820</span><span class="dib vm commodity__live_marketprice">市价1820</span><span class="dib vm commodity__live_buy icon_car"></span></div>  ';
    // if (content.firstChild == content.lastChild) {
    // content.appendChild(row);
    // } else {
    content.insertBefore(row, content.children[content.children.length - 1])
      // }
  }
  refreshElem.innerHTML = '更多';
  diff = container.offsetHeight - content.offsetHeight - 50;
  dd();
  scroller.setDimensions(container.clientWidth, container.clientHeight - 50, content.offsetWidth, content.offsetHeight - 50);
};
scroller.setDimensions(container.clientWidth, container.clientHeight - 50, content.offsetWidth, content.offsetHeight - 50);
// insertItems();

// Event Handler

if ('ontouchstart' in window) {

  container.addEventListener("touchstart", function(e) {
    // Don't react if initial down happens on a form element
    if (e.target.tagName.match(/input|textarea|select/i)) {
      return;
    }
    scroller.doTouchStart(e.touches, e.timeStamp);
    // e.preventDefault();
    e.stopPropagation();
  }, false);

  document.addEventListener("touchmove", function(e) {
    scroller.doTouchMove(e.touches, e.timeStamp);
    e.preventDefault();
    e.stopPropagation();
  }, false);

  document.addEventListener("touchend", function(e) {
    scroller.doTouchEnd(e.timeStamp);
    // e.preventDefault();
    e.stopPropagation();
  }, false);

}
